package com.qubuyer.business.auth.viewmodel

import androidx.lifecycle.MutableLiveData
import com.qubuyer.business.auth.model.AuthModel
import com.qubuyer.constant.AppConstant
import com.qubuyer.core.anno.AutoInject
import com.qubuyer.core.framework.BaseViewModel
import com.qubuyer.core.http.RetrofitCall
import com.qubuyer.repository.entitys.LoginEntity
import com.qubuyer.repository.entitys.ThirdLoginEntity

/**
 * Author: linwg
 * Time: 2021/2/5 0005
 * Description:
 */
class LoginViewModel : BaseViewModel() {

    @AutoInject
    private val authModel = AuthModel()
    val thirdPartLoginResult = MutableLiveData<Int>()
    val getCodeResult = MutableLiveData<Boolean>()
    val accountLoginType = MutableLiveData(true)
    var tempPwdText: String? = null
    var openId: String? = null
    var token: String? = null

    fun wxOrQQLogin(oauth: String, openId: String) {
        this.openId = openId
        RetrofitCall<ThirdLoginEntity?>(lifecycleOwner, this) {
            api { authModel.thirdPartLogin(oauth, openId) }
            success {
                thirdPartLoginResult.value = 200
            }
            fail { data, code, _ ->
                if(code == AppConstant.CODE_GO_SET_PWD){
                    token = data?.token
                }
                thirdPartLoginResult.value = code
            }
        }
    }

    fun getCode(phone: String) {
        RetrofitCall<String?>(lifecycleOwner, this) {
            api { authModel.getCode(phone) }
            success {
                getCodeResult.value = true
            }
            fail { _, _, _ ->
                getCodeResult.value = false
            }
        }
    }

    fun login(phone: String, code: String) {
        RetrofitCall<LoginEntity?>(lifecycleOwner, this) {
            api { if (accountLoginType.value == true) authModel.login(phone, code) else authModel.phoneLogin(phone, code) }
            success {
                thirdPartLoginResult.value = 200
            }
            fail { loginEntity, code, _ ->
                if(code == AppConstant.CODE_GO_SET_PWD){
                    token = loginEntity?.token
                }
                thirdPartLoginResult.value = code
            }
        }
    }
}